/**
 * 
 */
package com.wolfpire.proms.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.wolfpire.proms.model.ProjectIndex;
import com.wolfpire.proms.model.Task;
import com.wolfpire.proms.service.BiReportService;
import com.wolfpire.proms.service.ProjectIndexService;
import com.wolfpire.proms.service.TaskService;
import com.wolfpire.system.common.EasyuiPage;
import com.wolfpire.system.common.EasyuiPagination;
import com.wolfpire.system.common.Page;
import com.wolfpire.system.common.Result;
import com.wolfpire.system.common.excel2.ExcelCellData;
import com.wolfpire.system.common.excel2.ExcelTable;
import com.wolfpire.system.common.excel2.ExportExcel;

/**
 * 报表控制器
 * 
 * @author lihd
 *
 */

@Controller
@RequestMapping("/bireport")
public class BiReportController {

	@Resource
	BiReportService biReportService;

	@Resource
	ProjectIndexService projectIndexService;

	@Resource
	TaskService taskService;

	/**
	 * 任务增加量
	 * 
	 * @param portal
	 * @return
	 */
	@RequestMapping("/taskInc")
	public ModelAndView taskInc(
			@RequestParam(value = "portal", required = false) String portal) {
		ModelAndView mv = new ModelAndView("proms/bireport/task_inc");
		mv.getModel().put("portal",
				!StringUtils.isBlank(portal) ? portal : StringUtils.EMPTY);
		return mv;
	}

	/**
	 * 任务数量统计
	 * 
	 * @param portal
	 * @return
	 */
	@RequestMapping("/taskCount")
	public ModelAndView taskCount(
			@RequestParam(value = "portal", required = false) String portal) {
		ModelAndView mv = new ModelAndView("proms/bireport/task_count");
		if (!StringUtils.isBlank(portal)) {
			mv = new ModelAndView("proms/bireport/portal/task_count");
		}
		// mv.getModel().put("portal", !StringUtils.isBlank(portal) ? portal :
		// StringUtils.EMPTY);
		return mv;
	}

	@ResponseBody
	@RequestMapping("/taskCountData")
	public Result taskCountData(Long projectIndexId) {
		Result result = new Result();
		try {
			result.setSuccess(true);
			Map<String, Object> data = new HashMap<String, Object>();
			List<Map<String, Object>> lists = this.biReportService
					.findTaskCount(projectIndexId);
			data.put("piId", projectIndexId);
			ProjectIndex pi = this.projectIndexService.get(projectIndexId);
			data.put("ppiId", pi.getParentId());
			data.put("name", pi.getName());
			data.put("leaf", pi.isLeaf());
			data.put("data", lists);
			result.setData(data);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMessage("加载出错，请联系管理员！");
		}
		return result;
	}

	@ResponseBody
	@RequestMapping("/taskCountList")
	public EasyuiPagination<Map<String, Object>> taskCountList(
			EasyuiPage<Map<String, Object>> page,
			@RequestParam(value = "projectIndexId", required = true) Long projectIndexId,
			@RequestParam(value = "type", required = false) String type) {
		Page<Map<String, Object>> tasks = this.biReportService
				.setTaskCountList(page, projectIndexId, type);
		List<Map<String, Object>> tasksList = tasks.getDataList();
		Map<String, Object> total = null;
//		total.put("project_index_name", "小计");
//		Double fact_amount_ = 0.00;
//		Double pi_plan_amount_ = 0.00;
//		Double plan_amount_ = 0.00;
//		int count_ = 0;
//		Double unuser_pi_plan_amount_ = 0.00;
//		Double unuser_amount_ = 0.00;
		for (Map<String, Object> map : tasksList) {
//			if (map.get("fact_amount_") != null)
//				fact_amount_ += Double.parseDouble(map.get("fact_amount_")
//						.toString());
//			if (map.get("pi_plan_amount_") != null)
//				pi_plan_amount_ += Double.parseDouble(map
//						.get("pi_plan_amount_").toString());
//			if (map.get("plan_amount_") != null)
//				plan_amount_ += Double.parseDouble(map.get("plan_amount_")
//						.toString());
//			if (map.get("count_") != null)
//				count_ += Integer.parseInt(map.get("count_").toString());
//			if (map.get("unuser_pi_plan_amount_") != null)
//				unuser_pi_plan_amount_ += Double.parseDouble(map.get(
//						"unuser_pi_plan_amount_").toString());
//			if (map.get("unuser_amount_") != null)
//				unuser_amount_ += Double.parseDouble(map.get("unuser_amount_")
//						.toString());
			if(total == null){
				total = new HashMap<String, Object>();
				for (String key : map.keySet()) {
					if(key.indexOf("name")>-1){
						total.put(key, "小计");
					}else{
						total.put(key, 0.00);
					}
					
				}
			}
			for(String key : map.keySet()){
				if(map.get(key)!=null){
					if(key.indexOf("name")>-1){
						
					}else{
						try{
							Double value = Double.parseDouble(total.get(key).toString()) + Double.parseDouble(map.get(key).toString()) ;
							total.put(key, value);
						}catch(Exception e){
							
						}
					}
					
				}
			}
			
		}
//		total.put("fact_amount_", fact_amount_);
//		total.put("pi_plan_amount_", pi_plan_amount_);
//		total.put("plan_amount_", plan_amount_);
//		total.put("count_", count_);
//		total.put("unuser_pi_plan_amount_", unuser_pi_plan_amount_);
//		total.put("unuser_amount_", unuser_amount_);

		tasksList.add(total);

		return new EasyuiPagination<Map<String, Object>>(tasks);
	}

	/**
	 * 资金使用情况
	 * 
	 * @param portal
	 * @return
	 */
	@RequestMapping("/amountUse")
	public ModelAndView amountUse(
			@RequestParam(value = "portal", required = false) String portal) {
		ModelAndView mv = new ModelAndView("proms/bireport/amount_use");
		if (!StringUtils.isBlank(portal)) {
			mv = new ModelAndView("proms/bireport/portal/amount_use");
		}
		return mv;
	}

	@ResponseBody
	@RequestMapping("/amountUseData")
	public Result amountUseData(Long projectIndexId) {
		Result result = new Result();
		try {
			result.setSuccess(true);
			Map<String, Object> data = new HashMap<String, Object>();
			List<Map<String, Object>> lists = this.biReportService
					.findSumAmountUser(projectIndexId);
			data.put("piId", projectIndexId);
			ProjectIndex pi = this.projectIndexService.get(projectIndexId);
			data.put("ppiId", pi.getParentId());
			data.put("name", pi.getName());
			data.put("leaf", pi.isLeaf());
			data.put("data", lists);
			result.setData(data);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMessage("加载出错，请联系管理员！");
		}
		return result;
	}

	/**
	 * 资金投入情况
	 * 
	 * @param portal
	 * @return
	 */
	@RequestMapping("/amountInput")
	public ModelAndView amountInput(
			@RequestParam(value = "portal", required = false) String portal) {
		ModelAndView mv = new ModelAndView("proms/bireport/amount_input");
		mv.getModel().put("portal",
				!StringUtils.isBlank(portal) ? portal : StringUtils.EMPTY);
		return mv;
	}

	/**
	 * 任务进度情况统计
	 * 
	 * @param portal
	 * @return
	 */
	@RequestMapping("/taskProgress")
	public ModelAndView taskProgress(
			@RequestParam(value = "portal", required = false) String portal) {
		ModelAndView mv = new ModelAndView("proms/bireport/task_progress");
		if (!StringUtils.isBlank(portal)) {
			mv = new ModelAndView("proms/bireport/portal/task_progress");
		}
		return mv;
	}

	@ResponseBody
	@RequestMapping("/taskProgressData")
	public Result taskProgressData(Long projectIndexId) {
		Result result = new Result();
		try {
			result.setSuccess(true);
			Map<String, Object> data = new HashMap<String, Object>();
			List<Map<String, Object>> lists = this.biReportService
					.findCountTaskProgress(projectIndexId);
			data.put("piId", projectIndexId);
			ProjectIndex pi = this.projectIndexService.get(projectIndexId);
			data.put("ppiId", pi.getParentId());
			data.put("name", pi.getName());
			data.put("leaf", pi.isLeaf());
			data.put("data", lists);
			result.setData(data);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMessage("加载出错，请联系管理员！");
		}
		return result;
	}

	/**
	 * 根据权重值统计
	 * 
	 * @param portal
	 * @return
	 */
	@RequestMapping("/weightProgress")
	public ModelAndView weightProgressData(
			@RequestParam(value = "portal", required = false) String portal) {
		ModelAndView mv = new ModelAndView("proms/bireport/weight_progress");
		if (!StringUtils.isBlank(portal)) {
			mv = new ModelAndView("proms/bireport/portal/weight_progress");
		}
		return mv;
	}

	@ResponseBody
	@RequestMapping("/weightProgressData")
	public Result weightProgressData(Long projectIndexId) {
		Result result = new Result();
		try {
			result.setSuccess(true);
			Map<String, Object> data = new HashMap<String, Object>();
			List<Map<String, Object>> lists = this.biReportService
					.findWeightProgressData(projectIndexId);
			data.put("piId", projectIndexId);
			ProjectIndex pi = this.projectIndexService.get(projectIndexId);
			data.put("ppiId", pi.getParentId());
			data.put("name", pi.getName());
			data.put("leaf", pi.isLeaf());
			data.put("data", lists);
			result.setData(data);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMessage("加载出错，请联系管理员！");
		}
		return result;
	}

	@RequestMapping("/tasks")
	public ModelAndView tasks(Long projectIndexId) {
		return new ModelAndView("proms/bireport/task_list", "projectIndexId",
				projectIndexId);
	}

	@ResponseBody
	@RequestMapping("/queryTasks")
	public EasyuiPagination<Map<String, Object>> queryTasks(
			EasyuiPage<Map<String, Object>> page, Task filterTask) {
		Page<Map<String, Object>> tasks = this.taskService.setPageMyDataList(
				page, filterTask);
		return new EasyuiPagination<Map<String, Object>>(tasks);
	}

	@RequestMapping("/projectIndexMonitor")
	public ModelAndView projectIndexMonitor() {
		return new ModelAndView("proms/bireport/projectindex_monitor");
	}

	@ResponseBody
	@RequestMapping("/projectIndexMonitorData")
	public EasyuiPagination<Map<String, Object>> projectIndexMonitorData(
			EasyuiPage<Map<String, Object>> page, Long projectIndexId,
			String startTime, String endTime) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("projectIndexId", projectIndexId);
		if (StringUtils.isBlank(startTime)) {
			params.put("startTime", startTime);
		}
		if (StringUtils.isBlank(endTime)) {
			params.put("endTime", endTime);
		}
		Page<Map<String, Object>> projectIndexMonitors = this.biReportService
				.setProjectIndexMonitorDataList(page, params);
		return new EasyuiPagination<Map<String, Object>>(projectIndexMonitors);
	}
	
	@RequestMapping("/exportExcel")
	public void exportExcel(HttpSession session, 
			HttpServletRequest request, 
			HttpServletResponse response,
			@RequestParam(value = "projectIndexId", required = false) Long projectIndexId,
			@RequestParam(value = "type", required = false) String type) {
		try {
			List<Map<String, Object>> lists = this.biReportService.findTaskCountList(projectIndexId, type);
			ExcelTable table = xlsDto2Excel(lists, type, request);
			ExportExcel.exportExcel(request, response, table);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private ExcelTable xlsDto2Excel(List<Map<String, Object>> lists, String type, HttpServletRequest request) {
		ExcelTable table = new ExcelTable("任务统计表");
		Map<String, Object> xlsDto = new HashMap<String, Object>();
		int CountColumnNum = 7;
		if ("1".equals(type)) {
			CountColumnNum += 5;
		}
		if ("2".equals(type)) {
			CountColumnNum += 1;
		}
		String[] names = new String[CountColumnNum];
		names[0] = "指标名称";
		names[1] = "任务数";
		names[2] = "预算金额";
		names[3] = "已申请资金";
		names[4] = "已使用资金";
		names[5] = "剩余预算";
		names[6] = "待使用资金";
		
		if ("1".equals(type)) {
			names[7] = "[0%-25%]";
			names[8] = "[25%-50%]";
			names[9] = "[50%-75%]";
			names[10] = "[70%-99.99%]";
			names[11] = "[100%]";
		}
		
		if ("2".equals(type)) {
			names[7] = "权重比";
		}
		
		for (int j = 0; j < CountColumnNum; j++) {  
        	table.addData(new ExcelCellData(0,j,names[j]));
        }
		
		int k = 1;
        for (int i = 0; i < lists.size(); i++) {
        	xlsDto = lists.get(i);  
        	if(null!=xlsDto.get("project_index_name")){
        		table.addData(new ExcelCellData(k, 0, (String) xlsDto.get("project_index_name")));
        	}
        	if (null != xlsDto.get("count_")) {
        		table.addData(new ExcelCellData(k, 1, xlsDto.get("count_").toString()));
			} else {
				table.addData(new ExcelCellData(k, 1, "0"));
			}
        	if (null != xlsDto.get("pi_plan_amount_")) {
        		table.addData(new ExcelCellData(k, 2, xlsDto.get("pi_plan_amount_").toString()));
			} else {
				table.addData(new ExcelCellData(k, 2, "0.00"));
			}
        	if (null != xlsDto.get("plan_amount_")) {
        		table.addData(new ExcelCellData(k, 3, xlsDto.get("plan_amount_").toString()));
			} else {
				table.addData(new ExcelCellData(k, 3, "0.00"));
			}
        	if (null != xlsDto.get("fact_amount_")) {
        		table.addData(new ExcelCellData(k, 4, xlsDto.get("fact_amount_").toString()));
			} else {
				table.addData(new ExcelCellData(k, 4, "0.00"));
			}
        	if (null != xlsDto.get("unuser_pi_plan_amount_")) {
        		table.addData(new ExcelCellData(k, 5, xlsDto.get("unuser_pi_plan_amount_").toString()));
			} else {
				table.addData(new ExcelCellData(k, 5, "0.00"));
			}
        	if (null != xlsDto.get("unuser_amount_")) {
        		table.addData(new ExcelCellData(k, 6, xlsDto.get("unuser_amount_").toString()));
			} else {
				table.addData(new ExcelCellData(k, 6, "0.00"));
			}
        	if ("1".equals(type)) {
        		if (null != xlsDto.get("level1")) {
            		table.addData(new ExcelCellData(k, 7, xlsDto.get("level1").toString()));
    			} else {
    				table.addData(new ExcelCellData(k, 7, "0"));
    			}
        		if (null != xlsDto.get("level2")) {
            		table.addData(new ExcelCellData(k, 8, xlsDto.get("level2").toString()));
    			} else {
    				table.addData(new ExcelCellData(k, 8, "0"));
    			}
        		if (null != xlsDto.get("level3")) {
            		table.addData(new ExcelCellData(k, 9, xlsDto.get("level3").toString()));
    			} else {
    				table.addData(new ExcelCellData(k, 9, "0"));
    			}
        		if (null != xlsDto.get("level4")) {
            		table.addData(new ExcelCellData(k, 10, xlsDto.get("level4").toString()));
    			} else {
    				table.addData(new ExcelCellData(k, 10, "0"));
    			}
        		if (null != xlsDto.get("level5")) {
            		table.addData(new ExcelCellData(k, 11, xlsDto.get("level5").toString()));
    			} else {
    				table.addData(new ExcelCellData(k, 11, "0"));
    			}
			}
        	if ("2".equals(type)) {
        		if (null != xlsDto.get("progress")) {
            		table.addData(new ExcelCellData(k, 7, xlsDto.get("progress").toString()));
    			} else {
    				table.addData(new ExcelCellData(k, 7, "0.00"));
    			}
			}
        	k++;
        }
		return table;
	}
}
